package com.dc.service.dto.electronic;

import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.apache.commons.lang3.ObjectUtils;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Data
@AllArgsConstructor
@NoArgsConstructor
public class HttpGetPowerReturnNewBody implements Serializable {

    @JsonProperty("MfId")
    private String mfId;     // 参数id

    @JsonProperty("MName")
    private String mName;   // 仪表名称

    @JsonProperty("Data")
    private List<DDataInfo> data = new ArrayList<>();   // 参数用量值集合

    /**
     * 所有电能数据求和
     * @return
     */
    public Double getSum() {
        if(ObjectUtils.isEmpty(data)) {
            return 0.;
        }
        return data.stream().mapToDouble(DDataInfo::getValue).sum();
    }

    /**
     * 合并两个电表的电能数据
     * @param data1
     * @param data2
     * @return
     */
    public static List<DDataInfo> mergePower(List<DDataInfo> data1, List<DDataInfo> data2) {

//        List<DDataInfo> result = new ArrayList<>();

        if(ObjectUtils.isEmpty(data1) && ObjectUtils.isEmpty(data2)) {      // 全部为空
            return new ArrayList<>();
        }
        if(ObjectUtils.isEmpty(data1)) {            // dataList1 = null， 则取 dataList2
            data1.addAll(data2);
            return data1;
        }
        if(ObjectUtils.isEmpty(data2)) {            // dataList2 = null, 则取 dataList1
            return data1;
        }
        Map<Date, Double> dataMap1 = data1.stream().collect(Collectors.toMap(DDataInfo::getTime, DDataInfo::getValue));
        Map<Date, Double> dataMap2 = data2.stream().collect(Collectors.toMap(DDataInfo::getTime, DDataInfo::getValue));

        dataMap2.forEach((key, value) -> dataMap1.merge(key, value, Double::sum));

        List<DDataInfo> tmp = dataMap1.entrySet().stream().sorted(Map.Entry.comparingByKey())
                .map(e -> new DDataInfo(e.getKey(), e.getValue())).collect(Collectors.toList());

        return tmp;
    }
}
